package com.fyp.speachrecognition;



import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;
import java.util.Locale;

import com.fyp.MediaPlayer.MediaPlayerLibrary;
import com.fyp.database.DataProvider;
import com.fyp.database.User;
import com.fyp.settings.FileNames;
import com.fyp.settings.SettingsMain;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.media.MediaPlayer;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Environment;
import android.speech.RecognizerIntent;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class LogInActivity extends Activity implements OnInitListener{
	
	private final int VR_REQUEST = 909;
	private  EditText username, password;
	private Button speakBtn;
	private DataProvider dp;
	private final String LOG_TAG = "Speech Dialer";
	int LOGIN=1,USERNAME=2,PASSWORD=3,REUIRED_USER=4,REUIRED_PASS=5;
	int action=0;
	boolean flag=false;
	ConnectivityManager connManager=null;
	NetworkInfo mWifi=null, mMobile=null;
	Button loginBtn;
	MediaPlayer mrL = null;
	protected void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.login_activity);
		Log.v("Activity", "Login Activity Started");
		
		connManager = (ConnectivityManager)this. getSystemService(Context.CONNECTIVITY_SERVICE);
        mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI); 
        mMobile = connManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
        if (!mWifi.isConnected()||!mMobile.isConnected())
        {
        	/*try 
			{
				Class conmanClass = Class.forName(connManager.getClass().getName());
				Field iConnectivityManagerField;
				
					iConnectivityManagerField = conmanClass.getDeclaredField("mService");
					 iConnectivityManagerField.setAccessible(true);
					 Object iConnectivityManager;
				
						iConnectivityManager = iConnectivityManagerField.get(connManager);
						final Class iConnectivityManagerClass =  Class.forName(iConnectivityManager.getClass().getName());
			        	   Method setMobileDataEnabledMethod;
					
							setMobileDataEnabledMethod = iConnectivityManagerClass.getDeclaredMethod("setMobileDataEnabled", Boolean.TYPE);
							 setMobileDataEnabledMethod.setAccessible(true);

				        	   
								setMobileDataEnabledMethod.invoke(iConnectivityManager, true);
								StartActivity();
							} catch (InvocationTargetException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						catch (NoSuchMethodException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
			        	  
					 catch (IllegalArgumentException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IllegalAccessException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
		        	   
				catch (NoSuchFieldException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
	        	
			catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}*/
        	WifiManager wifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
        	  if(!wifiManager.isWifiEnabled())
        	  {
        		  wifiManager.setWifiEnabled(true);
        		  
        		 
        	  }
        	  
        		
        }
       
       
		loginBtn = (Button) findViewById(R.id.login_btn);
		 
		username=(EditText) findViewById(R.id.username);
		password=(EditText) findViewById(R.id.password);
		username.setSelected(true);
		dp = new DataProvider(this);
		speakBtn = (Button) findViewById(R.id.speakBtnLogin);
		
	
		 //find out whether speech recognition is supported
	    PackageManager packManager = getPackageManager();
	    List<ResolveInfo> intActivities = packManager.queryIntentActivities(new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
	    if (intActivities.size() != 0) 
	    {
	    	speakBtn.setOnClickListener(new View.OnClickListener()
	    	{
		
		 	@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
		 		if(MediaPlayerLibrary.isPlaying())
				{
					mrL.stop();
					mrL.release();
					MediaPlayerLibrary.setPlaying(false);
				}
				 
		 		Intent listenIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
	        	listenIntent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, getClass().getPackage().getName());
	        	listenIntent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Say a word!");
	        	listenIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
	        	listenIntent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 10);
	            startActivityForResult(listenIntent, VR_REQUEST);
		 		}
	    	});
	    	
	    	
	    	
	    	 
	    }
	    else
	    {
	    	//speech recognition not supported, disable button and output message
	       // speechBtn.setEnabled(false);
	    	Toast.makeText(this, "Oops - Speech recognition not supported!", Toast.LENGTH_LONG).show();
	   
	    }
		
		 loginBtn.setOnClickListener(new OnClickListener()
		 {

			@Override
			public void onClick(View v) 
			{
				// TODO Auto-generated method stub
				logingIn(username.getText().toString(),password.getText().toString());
			}
			 
		 });
		 TextView registerScreen = (TextView) findViewById(R.id.register_user);
		 
	        // Listening to register new account link
	        registerScreen.setOnClickListener(new View.OnClickListener() {
	 
	            public void onClick(View v) {
	                // Switching to Register screen
	                Intent i = new Intent(getApplicationContext(), RegistrationActivity.class);
	                startActivity(i);
	            }
	      });
	     
	       mrL= MediaPlayerLibrary.startPlayingFromRaw(this, R.raw.record_username_prompt);
	}
	protected void logingIn(String username,String pass) {
		// TODO Auto-generated method stub
	if(username.equals("")) 
		{

		  mrL= MediaPlayerLibrary.startPlayingFromRaw(this, R.raw.record_username_prompt);
		}
		else if(pass.equals(""))
			
		{
			  mrL= MediaPlayerLibrary.startPlayingFromRaw(this, R.raw.password_prmt);
		}
		else
		{
		
			User u = new User(username,pass);
			dp.open();
			if(dp.checkUserNamePass(u))
			{
				dp.close();
				Toast.makeText(getApplicationContext(), "Login Successful !!!", Toast.LENGTH_LONG).show();
				Intent i = new Intent(getApplicationContext(), SpeechDialer.class);
				i.putExtra("Login_success", true);
				startActivity(i);
			}
			else
			{
				dp.close();
				  mrL= MediaPlayerLibrary.startPlayingFromRaw(this, R.raw.login_error);
				Toast.makeText(getApplicationContext(), "Login Not Successful !!!", Toast.LENGTH_LONG).show();
			}
		}
		
               
	}
	
	protected void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		 
		  String wordChosen = null;
		action=0;
	    if (requestCode == VR_REQUEST && resultCode == RESULT_OK) 
	    {
	        ArrayList<String> suggestedWords = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
	      // wordList.setAdapter(new ArrayAdapter<String> (this, R.layout.word, suggestedWords));
	        ListIterator<String> it = suggestedWords.listIterator();
	        while(it.hasNext())
	        {
	        	wordChosen = it.next();
	        	Log.v(LOG_TAG, "auto word chosen: "+wordChosen);
	        	wordChosen.trim();
	        	wordChosen=wordChosen.toLowerCase(Locale.getDefault());
	        	wordChosen = constructString(wordChosen);
	        	if(!wordChosen.equalsIgnoreCase("login")&&username.getText().toString().length()==0)
	        	{
	        		action=USERNAME;
	        		flag=false;
	        	}
	        	else
	        	{ 
	        		if(!wordChosen.equalsIgnoreCase("login")&&username.getText().toString().length()!=0&&password.getText().toString().length()==0)
	        		{
	        			action=PASSWORD;
	        			flag=false;
	        		}
	        	
	        		else if(wordChosen.contains("login")&&username.getText().toString().length()!=0&&password.getText().toString().length()!=0)
	        		{
	        			action=LOGIN;
	        			flag=false;
	        		}
	        		else if(wordChosen.contains("login")&&username.getText().toString().length()!=0&&password.getText().toString().length()==0)
	        		{
	        			action=REUIRED_PASS;
	        			flag=false;
	        		}
	        		else if(wordChosen.contains("login")&&username.getText().toString().length()==0&&password.getText().toString().length()!=0)
	        		{
	        			action=REUIRED_USER;
	        			flag=false;
	        		}
	        	}
	        	
	        	 
	        	if(flag)
	        	{
	        		action=0;
	        	}
	        	else
	        	{
	        		break;
	        	}
	        	
	        }
	        
	        if(action==USERNAME)
	        {
	        	Log.v(LOG_TAG, "Username: "+wordChosen);
	        	username.setText(wordChosen);
	        	password.setSelected(true);
	        	 mrL= MediaPlayerLibrary.startPlayingFromRaw(this, R.raw.password_prmt);
				
	        }
	        else if (action==PASSWORD)
	        {
	        	Log.v(LOG_TAG, "Password: "+wordChosen);
	        	password.setText(wordChosen);
	        	password.setSelected(false);
	        }
	        else if(action==LOGIN)
	        {
	        	logingIn(username.getText().toString(),password.getText().toString());
	        	}
	        else if(action==REUIRED_USER)
	        {

	        	 mrL= MediaPlayerLibrary.startPlayingFromRaw(this, R.raw.record_username_prompt);
	        	Toast.makeText(LogInActivity.this, "Required User Name", Toast.LENGTH_SHORT).show();
	        }
	        else if(action==REUIRED_PASS)
	        {

	        	 mrL= MediaPlayerLibrary.startPlayingFromRaw(this, R.raw.password_prmt);
	        	Toast.makeText(LogInActivity.this, "Required Password", Toast.LENGTH_SHORT).show();
	        }
	        else if(action==0)
	        {
	        	 mrL= MediaPlayerLibrary.startPlayingFromRaw(this, R.raw.no_keyword_match);
	        	Toast.makeText(LogInActivity.this, "No Key Word Matches", Toast.LENGTH_SHORT).show();
	        }
	        
	    }
	    
	  
	    super.onActivityResult(requestCode, resultCode, data);
	}
	private String constructString(String wordChosen) {
		// TODO Auto-generated method stub
		StringBuilder sb = new StringBuilder();
		String[] s=wordChosen.split("[ ]");
		int i=0;
    	
		if(s.length>=2 && ((s[0].equals("user")&& s[1].equals("name"))||(s[0].equals("pass")&& s[1].equals("word"))))
    	{
			
    		sb.append(s[0]);
    		sb.append(s[1]);
    		i=2;
    	}
		else if(s.length>=1 && (s[0].equals("username") ||  s[0].equals("password")))
    	{
    		sb.append(s[0]);
    		i=1;
    	}
		
		if(i<s.length)
		{	
			sb.delete(0, sb.length());
			while (i<s.length)
			{
				sb.append(s[i]);
				i++;
			}
		}
		
		return sb.toString().trim();
	}
	public void onInit(int initStatus) 
	{ 
		
		   
	}
	
	@Override
	  protected void onResume() {
		
	    super.onResume();
	   
	  }

	  @Override
	  protected void onPause() {
		 
	    super.onPause();
	   
	    
	  }
	  protected void onDestroy()
	  {
		 
		 
		  super.onDestroy();
	  }
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
	    MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.menu.menu, menu);
	    return true;
	}
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	    // Handle item selection
	    switch (item.getItemId()) {
	        case R.id.Configuration:
	            record();
	            return true;
	        default:
	            return super.onOptionsItemSelected(item);
	    }
	}

	private void record() {
		// TODO Auto-generated method stub
		Intent i = new Intent(getApplicationContext(), SettingsMain.class);
		startActivity(i);
	}
}
